package com.chenyuhan.myview.testview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;

import com.chenyuhan.myview.R;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Chenyuhan on 2017/9/15.
 */

public class MyKeyboardView extends View implements View.OnTouchListener {
    private final String TAG = MyKeyboardView.class.getSimpleName();
    //键盘字母的颜色和大小
    private int mTextColor;
    private int mTextSize;

    //文本画笔
    private Paint mPaint;
    //背景画笔
    private Paint mBgPaint;


    //二十六个字母
    private String[] letters = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
    private String space = "Space";

    //点击位置的postion
    private int clickPosition = -1;
    //点击位置图片(字母和空格)
    private Bitmap clickDrawable;
    private Bitmap clickSpaceDrawable;


    //键盘点击监听
    private OnKeyBoardListener onKeyBoardListener;

    public MyKeyboardView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyKeyboardView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initSet();
        /**
         * 获得我们所定义的自定义样式属性
         */
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyKeyboardView, defStyleAttr, 0);
        for (int i = 0; i < typedArray.getIndexCount(); i++) {
            int attr = typedArray.getIndex(i);
            switch (attr) {
                case R.styleable.MyKeyboardView_keyBoardtextSize:
                    // 默认设置为16px，TypeValue也可以把px转化为sp
                    mTextSize = typedArray.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
                            TypedValue.COMPLEX_UNIT_PX, 16, getResources().getDisplayMetrics()));
                    break;
                case R.styleable.MyKeyboardView_keyBoardtextColor:
                    // 默认颜色设置为黑色
                    mTextColor = typedArray.getColor(attr, Color.BLACK);
                    break;
                case R.styleable.MyKeyboardView_pressedDrawable:
                    clickDrawable = BitmapFactory.decodeResource(getResources(), typedArray.getResourceId(attr, 0));
                    break;
                case R.styleable.MyKeyboardView_pressedSpaceDrawable:
                    clickSpaceDrawable = BitmapFactory.decodeResource(getResources(), typedArray.getResourceId(attr, 0));
                    break;
            }
        }
        typedArray.recycle();
        //设置文本画笔
        mPaint = new Paint();
        mPaint.setColor(mTextColor);
        mPaint.setTextSize(mTextSize);
        mPaint.setTextAlign(Paint.Align.CENTER);
        //设置背景画笔
        mBgPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL);
        setOnTouchListener(this);
    }

    /**
     * 初始化各种值
     */
    private void initSet() {
        mTextSize = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_PX, 16, getResources().getDisplayMetrics());
        mTextColor = Color.BLACK;

    }


    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        String text = "";
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                float x = motionEvent.getX();
                float y = motionEvent.getY();
                if (y < getHeight() / 6) {
                    //第一行
                    clickPosition = clickXPosition(x);
                    text = letters[clickPosition];
                } else if (y > getHeight() / 6 && y < getHeight() / 3) {
                    //第二行
                    clickPosition = clickXPosition(x) + 5;
                    text = letters[clickPosition];
                } else if (y > getHeight() / 3 && y < getHeight() / 2) {
                    //第三行
                    clickPosition = clickXPosition(x) + 10;
                    text = letters[clickPosition];
                } else if (y > getHeight() / 2 && y < getHeight() * 2 / 3) {
                    //第四行
                    clickPosition = clickXPosition(x) + 15;
                    text = letters[clickPosition];
                } else if (y > getHeight() * 2 / 3 && y < getHeight() * 5 / 6) {
                    //第五行
                    clickPosition = clickXPosition(x) + 20;
                    text = letters[clickPosition];
                } else if (y > getHeight() * 5 / 6 && y < getHeight()) {
                    //第六行
                    clickPosition = clickXPosition(x) == 0 ? 25 : 26;
                    text = clickPosition == 25 ? letters[25] : space;
                }
                onKeyBoardListener.onKeyBoardClickListener(text);
                //刷新View，显示点击效果
                postInvalidate();
                break;
            case MotionEvent.ACTION_UP:
                clickPosition = -1;
                //刷新View，取消点击效果
                postInvalidate();
                break;
        }
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
        float top = fontMetrics.top;//为基线到字体上边框的距离
        float bottom = fontMetrics.bottom;//为基线到字体下边框的距离
        //画前五行的字母
        for (int y = 0; y < 5; y++) {
            //文本的baseline的y坐标
            int baseLineY = 0;
            //列
            for (int x = 0; x < 5; x++) {
                int position = y * 5 + x;
                //获得所要画的文本
                String text = letters[position];
                //点击时背景图片矩形大小，这里计算也是为了方便之后计算基线的y轴坐标
                Rect imageRect = new Rect();
                imageRect.left = position % 5 * getWidth() / 5;
                imageRect.top = position / 5 * getHeight() / 6;
                imageRect.right = imageRect.left + getWidth() / 5;
                imageRect.bottom = imageRect.top + getHeight() / 6;
                //如果该位置处于点击状态
                if (position == clickPosition) {
                    canvas.drawBitmap(clickDrawable, null, imageRect, mBgPaint);
                }
                //基线中间点的y轴计算公式
                baseLineY = (int) (imageRect.centerY() - top / 2 - bottom / 2);
                //画文本，第二个参数为所占矩形的X轴中心，第三个为基准线Y坐标
                canvas.drawText(text, imageRect.centerX(), baseLineY, mPaint);
            }
        }
        //第六行
        Rect imageRect = new Rect();
        imageRect.left = 0;
        imageRect.top = 5 * getHeight() / 6;
        imageRect.right = getWidth() / 5;
        imageRect.bottom = imageRect.top + getHeight() / 6;
        if (clickPosition == 25)
            canvas.drawBitmap(clickDrawable, null, imageRect, mBgPaint);
        int sixLineBaseLineY = (int) (imageRect.centerY() - top / 2 - bottom / 2);
        canvas.drawText(letters[25], imageRect.centerX(), sixLineBaseLineY, mPaint);

        imageRect.left = getWidth() * 1 / 5;
        imageRect.right = getWidth();
        if (clickPosition == 26)
            canvas.drawBitmap(clickSpaceDrawable, null, imageRect, mBgPaint);
        canvas.drawText(space, imageRect.centerX(), sixLineBaseLineY, mPaint);
    }

    public void setOnKeyBoardListener(OnKeyBoardListener onKeyBoardListener) {
        this.onKeyBoardListener = onKeyBoardListener;
    }

    /**
     * 计算所点击的x轴坐标对应每行的第几个字母
     *
     * @param x 点击下的x坐标
     * @return 所点击的位置
     */
    private int clickXPosition(float x) {
        int position = 0;
        if (x < getWidth() / 5)
            position = 0;
        else if (x > getWidth() / 5 && x < getWidth() * 2 / 5)
            position = 1;
        else if (x > getWidth() * 2 / 5 && x < getWidth() * 3 / 5)
            position = 2;
        else if (x > getWidth() * 3 / 5 && x < getWidth() * 4 / 5)
            position = 3;
        else if (x > getWidth() * 4 / 5 && x < getWidth())
            position = 4;

        return position;
    }

    public interface OnKeyBoardListener {
        /**
         * 控件点击监听
         *
         * @param text 所点击的文本
         */
        void onKeyBoardClickListener(String text);
    }


}